package com.ts.notice.job;

import com.ts.notice.constants.RedisKey;
import com.ts.notice.dto.SMSDto;
import com.ts.notice.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;

@EnableScheduling
@Component
@Slf4j
public class SmsJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SMSUtils smsUtils;

    //    @Scheduled(cron = "* * * * * *")
    public void reSendSms() {

        // 1.先从redis中查询发送失败的短信
        Set set = redisTemplate.opsForSet().members(RedisKey.SEND_SMS_ERROR_KEY);

        // 2.如果没有短信直接结束
        if (set.isEmpty() || set.size() == 0) {
            log.debug("本次任务结束，没有需要发送的短信");
            return;
        }

        // 3.循环发送
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            SMSDto smsDto = (SMSDto) iterator.next();

            // 再次查询这个短信是否发送成功
            Boolean flag = smsUtils.query(smsDto.getTaskId(), smsDto.getMobile());
            if (!flag) {
                // 需要重新发送了
                SMSDto newSMDeo = new SMSDto();
                BeanUtils.copyProperties(smsDto,newSMDeo);
                smsUtils.send(newSMDeo);
            }
            // 这个短信已经发送成功了，需要删除
            redisTemplate.opsForSet().remove(RedisKey.SEND_SMS_ERROR_KEY, smsDto);
        }

    }
}
